package com.weipai.demo.util;

import com.alibaba.fastjson.JSON;
import com.weipai.demo.enums.RetCode;
import com.weipai.demo.model.DUser;
import com.weipai.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginHandlerInterceptor.class);
    public static final String AUTH_TOKEN_HEADER = "Authentication-Token";
    @Autowired
    private UserService userService;

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String authToken = request.getHeader(AUTH_TOKEN_HEADER);
        Response ret = new Response();
        if (authToken != null&&!authToken.equals("")) {
            //app端
            boolean isValid = false;
            try {
                isValid = com.weipai.demo.util.PasswordHelper.validateToken(authToken);
            } catch (Exception e) {
                logger.error("validate token with error = {}", e);
            }
            if (isValid) {
                //已登录


                    String username = com.weipai.demo.util.PasswordHelper.getUserName(authToken);
                    DUser user = userService.getUserByLoginName(username);
                    if (user == null) {
                        //返回未登录
                        ret.setCode(RetCode.NOT_LOGIN);
                        response.setCharacterEncoding("utf-8");
                        response.getWriter().append(JSON.toJSONString(ret));
                        return false;
                    }

                return true;
            } else {
                //返回未登录
                response.setCharacterEncoding("utf-8");
                ret.setCode(RetCode.NOT_LOGIN);
                response.getWriter().append(JSON.toJSONString(ret));
                return false;
            }

        }/*else{
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            User user = (User) session.getAttribute(User.KEY);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            if (user == null) {
               *//* ret.setCode(RetCode.NOT_LOGIN);
                response.getWriter().append(JSON.toJSONString(ret));*//*
                return true;
            } else {
                return true;
            }
        }*/
        return true;
        }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
